package com.concurrency.cf.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MethodTest {

    public static void main(String[] args) {
        // runAsync(), supplyAsync(), thenAccept()
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 入参是Runnable，没有返回值
        CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }, executorService);
        System.out.println(Thread.currentThread().getName());
        while (true) {
            if (cf.isDone()) {
                System.out.println("cf is down");
                break;
            }
        }
        // 入参是Supplier，有返回值
        CompletableFuture<Void> cf1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return "1111";
        }, executorService)
                .thenAccept(s -> System.out.println(Thread.currentThread().getName() + ", " + s));
        while (true) {
            if (cf1.isDone()) {
                System.out.println("cf1 is down");
                break;
            }
        }

        // 任务执行中报错了，怎么直接中断，并抛出异常
        List<Throwable> errorMessage = new ArrayList<>();
        CompletableFuture<Void> cf2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            if (1 == 1) {
                throw new RuntimeException("测试异常");
            }
            return "1111";
        }, executorService).exceptionally(e -> {
            System.out.println(e.getMessage());
            errorMessage.add(e);
            return "hello world, " + e.getMessage();
        }).thenAccept(s -> System.out.println(Thread.currentThread().getName() + ", " + s));

        cf2.join();

        if (errorMessage.size() > 0) {
            System.out.println("抛出异常");
            executorService.shutdown();
            throw new RuntimeException(errorMessage.get(0).getMessage());
        }

        System.out.println(Thread.currentThread().getName());

    }

}
